import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;


//二叉树的层平均值
public class Solution4 {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            double sum = 0;
            int i = size;
            while (size != 0) {
                TreeNode tmp = queue.remove();
                size--;
                sum += tmp.val;
                if (tmp.left != null) {
                    queue.offer(tmp.left);
                }
                if (tmp.right != null) {
                    queue.offer(tmp.right);
                }

            }
            double avg = sum / i;
            sum = 0;
            list.add(avg);
        }
        return list;

    }
    public static void main(String[] args) {

    }
}
